package com.caiyi.tips.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.caiyi.tips.core.Constant.PublicConstant;
import com.caiyi.tips.core.VO.ResultVO;
import com.caiyi.tips.core.enums.ResultEnum;
import com.caiyi.tips.core.util.CheckUtil;
import com.caiyi.tips.core.util.IdCreator;
import com.caiyi.tips.user.bean.ExpertBean;
import com.caiyi.tips.user.bean.SmsBean;
import com.caiyi.tips.user.bean.TokenBean;
import com.caiyi.tips.user.bean.UserBean;
import com.caiyi.tips.user.exception.UserException;
import com.caiyi.tips.user.mapper.ExpertMapper;
import com.caiyi.tips.user.service.ExpertService;
import com.caiyi.tips.user.service.SmsService;
import com.caiyi.tips.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/*
 * @author Cliff.ZhouYang
 * @date 2017/11/8 15:59
 */
@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class ExpertServiceImpl implements ExpertService {
    @Autowired
    private SmsService smsService;
    @Autowired
    private UserService userService;
    @Autowired
    private ExpertMapper expertMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultVO register(ExpertBean expertBean, HttpServletRequest request) {
        /**
         * 1.校验参数是否为空
         * 2.验证手机号
         * 3.生成cuserId (生成策略：uuid)
         * 4.入库生成 专家表
         */
        if (expertMapper.checkExpertExistPhone(expertBean.getPhone()) > 0) {
            throw new UserException("手机号已存在");
        }
        if (expertMapper.checkExpertExistNickid(expertBean.getNickid()) > 0) {
            throw new UserException("用户名已存在");
        }
        SmsBean smsBean = new SmsBean();
        BeanUtils.copyProperties(expertBean, smsBean);
        smsService.checkSmsYzm(smsBean);
        this.createExpert(expertBean);

        HttpSession session = request.getSession();
        session.setAttribute(PublicConstant.PASSWORD_KEY, expertBean.getPhone());
        session.setAttribute(PublicConstant.USERNAME_KEY, expertBean.getPassword());

        return new ResultVO(ResultEnum.SUCCESS.getCode(), "注册成功", JSONObject.parse("{pass:0,success:1}"));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ExpertBean createExpert(ExpertBean expertBean) {
        //userBean.setCloginfrom(userBean.getCbelongValue());

        String userid = IdCreator.uuid();
        expertBean.setUserid(userid);

        String password = expertBean.getPassword();
        if (!StringUtils.isEmpty(password)) {
            password = DigestUtils.md5Hex(password);
            expertBean.setPassword(password);
        }
        this.saveExpert(expertBean);
        return expertBean;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int saveExpert(ExpertBean expertBean) {
        return expertMapper.saveExpert(expertBean);
    }

//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public TokenBean createTokenBean(UserDTO userDTO) {
//
//        /**
//         * 校验是否注销用户
//         */
//        CancellationUserBean cancellationUserBean = new CancellationUserBean();
//        cancellationUserBean.setCuserId(userBean.getCuserId());
//        cancellationUserBean.setCancellationValue(userBean.getCloginfrom());
//        if (cancellationUserService.getCountByCuserIdAndCancellationValue(cancellationUserBean) > 0) {
//            throw new UserException(TokenCodeConstant.LOGIN_TOKEN_ACCOUNT_FORBIDDEN, "用户已经注销");
//        }
//
//        TokenBean token = new TokenBean();
//        String appId = UniqueStrCreator.createUniqueString(tokenConfigurationProperties.getAppidPrefix());
//        String accessToken = TokenGenerator.createToken(appId);
//        token.setAccessToken(accessToken);
//        token.setAppId(appId);
//        token.setCuserId(userBean.getCuserId());
//        token.setCloginfrom(userBean.getCloginfrom());
//        token.setExpiresin(tokenConfigurationProperties.getDefaultExpiresin());
//        token.setMobileType(userBean.getMobileType());
//        token.setCreateTime(new Date());
//        token.setCnickId(userBean.getCnickId());
//        tokenService.saveToken(token);
//        return token;
//    }
    public ResultVO login(ExpertBean expertBean) {
        String password = DigestUtils.md5Hex(expertBean.getPassword());
        ExpertBean bean;
        if (CheckUtil.isMobilephone(expertBean.getUserid())) {
            //手机号登录
            bean = expertMapper.findExpertByPhone(expertBean.getPhone());
        } else {
            bean = expertMapper.findExpertByNickid(expertBean.getUserid());
            //用户名登录

        }
        if (bean == null) {
            throw new UserException("用户不存在");
        }
        if (bean.getPassword() == null) {
            throw new UserException("密码不存在");
        }
        if (!password.equals(bean.getPassword())) {
            throw new UserException("用户名或密码错误");
        }
        TokenBean tokenBean = null;//this.createTokenBean()

        return ResultVO.okData(tokenBean);
    }

}
